package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.domain.Menu;
import com.ml4ai.backend.dto.MenuDTO;
import com.ml4ai.backend.repository.MenuRepository;
import com.ml4ai.backend.utils.Bean2Bean;
import com.ml4ai.backend.utils.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by uesr on 2018/9/3.
 */
@Component
public class MenuMapper extends BaseMapper<Menu, MenuDTO> {

    @Autowired
    MenuRepository menuRepo;

    @Override
    public Menu newEntity() {
        return new Menu();
    }

    @Override
    public MenuDTO newDTO() {
        return new MenuDTO();
    }

    @Override
    public Menu find(Long id) {
        return menuRepo.findOne(id);
    }

    @Override
    public void entity2dto(Menu entity, MenuDTO dto) {
        new Bean2Bean().addPropMapper(new PropertyMapper<>("parent", this::e2d)).copyProperties(entity, dto);
        if (entity.getParent() != null) {
            dto.setParentId(entity.getParent().getId());
        }
    }

    @Override
    public void dto2entity(MenuDTO dto, Menu entity) {
        new Bean2Bean().addExcludeProp("parent").addExcludeProp(Const.getNotCopyAuditFields()).copyProperties(dto, entity);
        if (dto.getParentId() != null)
            entity.setParent(find(dto.getParentId()));
        else if (dto.getParent() != null && dto.getParent().getId() != null)
            entity.setParent(find(dto.getParent().getId()));
        else
            entity.setParent(null);
    }
}
